package eu.testing.system.controllers;

import java.util.logging.Logger;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.ui.ModelMap;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import eu.testing.system.dao.AnswerDao;
import eu.testing.system.dao.AssignedDao;
import eu.testing.system.dao.QuestionDao;
import eu.testing.system.dao.ResultDao;
import eu.testing.system.dao.TestDao;
import eu.testing.system.dao.UserDataDao;
import eu.testing.system.dao.VariantDao;

public class SystemController {

	public ApplicationContext context = new ClassPathXmlApplicationContext(
			"Spring-Module.xml");
	public UserDataDao userDataDao = (UserDataDao) context
			.getBean("UserDataDao");
	public ResultDao resultDao = (ResultDao) context.getBean("ResultDao");

	public TestDao testDao = (TestDao) context.getBean("TestDao");

	public AssignedDao assignedDao = (AssignedDao) context
			.getBean("AssignedDao");

	public VariantDao variantDao = (VariantDao) context.getBean("VariantDao");

	public AnswerDao answerDao = (AnswerDao) context.getBean("AnswerDao");

	public QuestionDao questionDao = (QuestionDao) context
			.getBean("QuestionDao");

	public User getUser() {
		return (User) SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();

	}

	public Logger logger = Logger.getLogger(TestController.class.getName());

	public ModelMap addUserData(ModelMap model) {
		User user = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		model.addAttribute("username", user.getUsername());
		model.addAttribute("role", user.getAuthorities());
		return model;

	}

	public String getUsername() {
		return getUser().getUsername().toString();
	}

	public String getAuthority() {
		return getUser().getAuthorities().toString();
	}

	public Object getObjectFromJson(String json, Class<?> classObject) {
		Gson gson = new GsonBuilder().create();
		Object object = gson.fromJson(json, classObject);
		return object;

	}

	public boolean isAdmin() {
		User user = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		return user.getAuthorities().toString().equals("[ROLE_ADMIN]");

	}

}
